<template>
  <div class="container">
    <FmTable ref="fmTable" url="/process/admin" tableName="role" :columns="columns">
      <template #opt="scope">
        <el-button
            type="primary"
            icon="Setting"
            link
            @click="editUserRole(scope.row.id)"
        >角色关联
        </el-button>
        <el-button
            type="primary"
            icon="Coin"
            link
            @click="openResource(scope.row)"
        >资源
        </el-button>
        <el-button
            type="primary"
            link
            icon="Edit"
            @click="fmTable.handleEdit(scope.$index, scope.row)"
        >编辑
        </el-button>
      </template>
    </FmTable>
    <el-dialog title="角色权限" v-model="userRightVisible" :before-close=" ()=>{userRightVisible=false}" width="20%">
      <div style="height:300px;" class="scrollbar">
        <el-scrollbar style="height:100%">
          <el-tree
              :props="props"
              node-key="id"
              :data="AllResource"
              @check-change="handleCheckChange"
              show-checkbox
              ref="addtree"
          >
            <template #default="{ node, data }">
      <span class="custom-tree-node">
        <span>
            <i :class="data.icon"></i>{{ node.label }}
        </span>
       </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
      <template #footer>
        <el-button @click="userRightVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleResourse">确 定</el-button>
      </template>
    </el-dialog>
    <!--    -->
    <el-dialog title="角色用户关联" v-model="userRolelVisible" :before-close=" ()=>{userRolelVisible=false}"
               width="50%">
      <el-transfer
          filterable
          filter-placeholder="请输入城市拼音"
          v-model="RoleUserList"
          :titles="['用户列表', '角色用户']"
          :data="NoRoleUserList">
      </el-transfer>
      <template #footer>
        <el-button @click="userRolelVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRole">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import FmTable from '@/components/common/Table/FmTable.vue'
import {nextTick, onMounted, reactive, ref} from "vue";
import {ElTree, ElMessage} from 'element-plus'
import {fetchData, saveorUpadateDate} from "@/api";
const columns = [
  {
    "label": "主键",//标签名称
    "index": "id",//数据库索引
    "rules": [
      {required: true, message: "请输入主键", trigger: "blur",},
    ],//值规则
    "addable": false,
    "upd-disabled": true
  },
  {
    "label": "角色",//标签名称
    "index": "name",//数据库索引
    "rules": [
      {required: true, message: "请输入主键", trigger: "blur",},
    ],//值规则
    "search": true,//是否是搜索表单
  },
  {
    "label": "描述",//标签名称
    "index": "desc",//数据库索引
    "rules": [
      {required: true, message: "请输入主键", trigger: "blur",},
    ],//值规则
  },
  {
    "type": "opt",//普通行，字典行，自定义行
    "label": "操作",//标签名称
    "index": "opt",//数据库索引
    "rules": [],//值规则
  }
]
let fmTable = ref()
let NoRoleUserList = ref([])
let RoleUserList = ref([])
let props = reactive({
  id: 'id',
  label: 'name',
  children: 'children'
})
let userRightVisible = ref(false)
let userRolelVisible = ref(false)
let userRole = reactive([])
let userdata = reactive([])
let AllResource = reactive([])
let roleAllResource = reactive([])
let roleId = ref("")
let addtree = ref<InstanceType<typeof ElTree>>()
let form = reactive({})
let ids = reactive([])
const getAllResource = () => {
  fetchData('/process/admin/resource/tree').then((res: any) => {
    AllResource = res;
  });
}
const handleCheckChange = (data: any, checked: any, indeterminate: any) => {
  //获取所有选中的节点 start
  let res = addtree.value!.getCheckedNodes().concat(addtree.value!.getHalfCheckedNodes())
  let arrDeptId = []
  res.forEach((item) => {
    if (item.id != undefined) {
      arrDeptId.push(item.id)
    }
  })
  ids = arrDeptId
}
const openResource = (role: any) => {
  form = role
  userRightVisible.value = true
  nextTick(() => {
    addtree.value!.setCheckedKeys([])
  })
  fetchData("/process/admin/role/getRoleResourceList/" + role.id).then((res: any) => {
    nextTick(() => {
      res.forEach(
          value => {
            var node = addtree.value!.getNode(value);
            if (node && node.isLeaf) {
              addtree.value!.setChecked(value, true, false)
            }
          }
      )
    })
  })
}

const saveRoleResourse = () => {
  form.resourceIds = ids;
  saveorUpadateDate('/process/admin/role/saveRoleResource', form).then(res => {
    ElMessage.success("保存成功")
    userRightVisible.value = false
    window.location.href = "/"
  })
}
const editUserRole = (roleid:any) => {
  NoRoleUserList = ref([])
  RoleUserList = ref([])
  roleId.value = roleid
  userRolelVisible.value = true
  fetchData("/process/admin/role/getRoleUserList/" + roleId.value).then((res:any) => {
    nextTick(()=> {
      for (let i = 0; i < res.NoRoleUserList.length; i++) {
        NoRoleUserList.value.push({
          key: res.NoRoleUserList[i].id,
          label: res.NoRoleUserList[i].name,
          disabled: false
        })
      }
      for (let i = 0; i < res.RoleUserList.length; i++) {
        NoRoleUserList.value.push({
          key: res.RoleUserList[i].id,
          label: res.RoleUserList[i].name,
          disabled: false
        })
        RoleUserList.value.push(res.RoleUserList[i].id)
      }
    })
  })
}
const saveUserRole = () => {
   debugger
    let data={};
    data.roleId=roleId.value
    data.userIds=RoleUserList.value;
    saveorUpadateDate('/process/admin/role/saveRoleUserList', data).then(res => {
        ElMessage.success("保存成功")
        userRolelVisible.value=false
        roleId.value=""
      })
}
onMounted(()=>{
  getAllResource()
})

</script>
<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

</style>